//
//  SXPhomeViewController.swift
//  weibo
//
//  Created by shixinPeng on 16/2/24.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class SXPhomeViewController: SXPbaseTableViewController {

   //定义一个全局属性
    var viewModel:SXPhomeViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        
       visitor?.setInfo("登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过", image: "visitordiscover_feed_image_smallicon", animoution: true)
       
        if isLogin {
            
            //获取实例
            viewModel = SXPhomeViewModel()
            //下载数据
            loadData()
            //注册cell
            tableView.registerClass(SXPHomeTableViewCell.self, forCellReuseIdentifier: kHomeTableViewCell)
            
            //设置自动行高
            tableView.rowHeight = UITableViewAutomaticDimension
            //设置预设行高
            tableView.estimatedRowHeight = 200
            //添加菊花
            tableView.tableFooterView = PullView
   
            
           // PullView.color = UIColor.orangeColor()
            
            tableView.addSubview(refreshView)
            
            //添加触发事件
            refreshView.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
  
        }
        
    }
     @objc private func loadData() {
        
        SVProgressHUD.show()
        //上拉更多获取最新数据
        //取最上面的id
        //去下载数据 上提更多需要要since_id 设为0,根据max_id 的值来下载以前的数据,(加载比这个id小的数据)
        var since_id = viewModel?.statusesArray.first?.statusesModel?.id ?? 0
        

        var max_id = 0
        //获取max_id
        if PullView.isAnimating(){
            since_id = 0
            
           max_id = viewModel?.statusesArray.last?.statusesModel?.id ?? 0
            //要保证没有重复的
            max_id -= 1
        }
        
        
        viewModel?.loadData(since_id: since_id, max_id: max_id, FinishClosure: { (result) -> () in
            self.tableView.reloadData()
            SVProgressHUD.dismiss()
            
            if !self.PullView.isAnimating() {
                //结束下载状态
                self.refreshView.endResFreshing()
                //显示下载数据的数量
                self.showLoaddateCount(result)}
            }, failes: { (error) -> () in
                SVProgressHUD.dismiss()
            printLog(error)
        })
        
        
        /*
        
        viewModel?.loadData(since_id: since_id, max_id: max_id, FinishClosure: { (result) -> () in
        //网络请求成功后的回调
        self.tableView.reloadData()
        SVProgressHUD.dismiss()
        //上拉的时候没有提示模块
        if !self.PullView.isAnimating() {
        //结束下载状态
        self.refreshView.endResFreshing()
        //显示下载数据的数量
        self.showLoaddateCount(result)}
        }, failes: {(error) -> () in
        
        printLog(error)
        }
        
        
        */
        
   
    }
    
    @objc private func showLoaddateCount(result:NSInteger) {
        
        if result < 0 {
            
            return
        }
        //第一次刷新界面不显示
        if viewModel?.statusesArray.count == 20 {
            return
        }
        //创建一个label.
        let labelHeight:CGFloat = 44
        
        let Countlabel:UILabel = UILabel()
        
        //设置属性
        Countlabel.frame = CGRectMake(0, 64 - labelHeight, kUISCREEN_W, labelHeight)
        //设置背景色
        Countlabel.backgroundColor = UIColor.orangeColor()
        if result == 0{
            Countlabel.text = "暂时没有更新哟!"
        }else{
            Countlabel.text = "更新了\(result)条数据"
        }
        Countlabel.textAlignment = .Center
        //把控件添加到界面上
        navigationController?.view.insertSubview(Countlabel, belowSubview: navigationController!.navigationBar)
        
        //动画显示--> 显示完之后消失
        UIView.animateWithDuration(2, animations: { () -> Void in
            //让label出来
            Countlabel.transform = CGAffineTransformMakeTranslation(0, labelHeight)
            }) { (_) -> Void in
               //让图像消失
                UIView.animateWithDuration(2, animations: { () -> Void in
                    Countlabel.alpha = 0
                    }, completion: { (_) -> Void in
                        Countlabel.removeFromSuperview()
                })
        }
        
        
        
    }
    //懒加载
    private lazy var PullView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    private lazy var refreshView:SXPrefreshView = SXPrefreshView()
}

///  mark:tableViewController的数据源方法
extension SXPhomeViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.statusesArray.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(kHomeTableViewCell, forIndexPath: indexPath) as! SXPHomeTableViewCell
        
        //cell.textLabel?.text = viewModel?.statusesArray[indexPath.row].statusesModel?.text
        
        cell.statusesviewModel = viewModel?.statusesArray[indexPath.row]
        
        
        //判断什么时候发送下载请求
        if indexPath.item == ((self.viewModel?.statusesArray.count)! - 1) && !PullView.isAnimating() {
            
            PullView.startAnimating()
      
            loadData()
            
        }
        
        
        return cell
    }
    
//    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//        
////        //设置动画时间为0.25秒,xy方向缩放的最终值为1
////        cell.layer.transform =CATransform3DMakeScale(0.8,0.8, 1);
////        
////        [UIView animateWithDuration:1 animations:^{
////            //             cell.layer.transform =CATransform3DMakeScale(0.95,0.95, 1);
////            cell.layer.transform =CATransform3DMakeScale(1,1, 1);
////            //            cell.layer.transform =CATransform3DMakeScale(0.9,0.9, 1);
////            } completion:^(BOOL finished) {
////            
////            }];
//        cell.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1)
//        
//        UIView.animateWithDuration(1) { () -> Void in
//            cell.layer.transform = CATransform3DMakeScale(1,1, 1)
//        }
//    
//    }
}
